import React from 'react'
import './Chat.css'
import axios from 'axios'
import ChatWindow from './ChatWindow'
// import {Toast,Button} from 'antd-mobile'

export default class Chat extends React.Component {
  constructor() {
    super()

    this.state = {
      messageList: [], //消息列表
      isShowChatWindow: false, //是否显示聊天窗口
      currentInfo: null //当前点击的聊天的那条记录
    }
  }

  async componentDidMount() {
    const res = await axios.post('chats/list')

    this.setState({
      messageList: res.data.list
    })
  }

  // 显示聊天窗口
  /** 
  showChatWindow = item => {
    this.setState({
      isShowChatWindow:!this.state.isShowChatWindow
    })
  }
  */
  showChatWindow = item => {
    this.setState({
      currentInfo: item
    })

    this.setState({
      isShowChatWindow: !this.state.isShowChatWindow
    })
  }

  hideChatWindow = () => {
    this.setState({
      isShowChatWindow: false
    })
  }

  // showToast = () => {
  //   Toast.info("aaaaa")
  // }

  render() {
    const { messageList, isShowChatWindow, currentInfo } = this.state

    /** 时间格式化 */
    function formatNumber(n) {
      const str = n.toString()
      return str[1] ? str : `0${str}`
    }

    const date_format = input => {
      const date = new Date(input)

      const year = date.getFullYear()
      const month = date.getMonth() + 1
      const day = date.getDate()

      const hour = date.getHours()
      const minute = date.getMinutes()
      const second = date.getSeconds()

      const t1 = [year, month, day].map(formatNumber).join('/')
      const t2 = [hour, minute, second].map(formatNumber).join(':')

      return `${t1} ${t2}`
    }

    // 根据数据生成lis
    const lis = messageList.map(item => {
      return (
        // <li onClick={this.showChatWindow.bind(this, item)} key={item.id}>
        <li
          onClick={() => {
            this.showChatWindow(item)
          }}
          key={item.id}
        >
          <div className="avarter">
            <img src="http://47.96.21.88:8086/public/icon.png" alt="avarter" />
            <span className="name">{item.username}</span>
            <span className="info">{item.chat_msg}</span>
            <span className="time">{date_format(item.ctime)}</span>
          </div>
        </li>
      )
    })

    return (
      <div className="chat-container">
        {isShowChatWindow && (
          <ChatWindow currentInfo={currentInfo} hideChatWindow={this.hideChatWindow} />
        )}
        <div className="chat-title">聊天</div>
        {/* <Button onClick={this.showToast} type="warning">点击测试Toast</Button> */}
        <div className="chat-list">
          <ul>{lis}</ul>
        </div>
      </div>
    )
  }
}
